/**

This file is part of MaCI/GIMnet.

MaCI/GIMnet is free software: you can redistribute it and/or modify it 
under the terms of the GNU Lesser General Public License as published 
by the Free Software Foundation, either version 3 of the License, or 
(at your option) any later version.

MaCI/GIMnet is distributed in the hope that it will be useful, but WITHOUT 
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public 
License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with GIMnet. (See COPYING.LESSER) If not, see 
<http://www.gnu.org/licenses/>.

**/
/**
 * \file
 * \brief Implementation for SQL interface client library.
 * \author Antti Maula <antti.maula@tkk.fi>
 *
 * $Id: SQLClient.cpp,v 1.9 2009-10-26 12:47:02 morsko Exp $
 *
 */

#include "SQLClient.hpp"
#include "SQLData.hpp"

//*****************************************************************************
using namespace MaCI::SQL;
//*****************************************************************************
//*****************************************************************************
#define GIMI_CLIENT_API (20000)
#include "gimi.h"
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************

CSQLClient::CSQLClient(gimi::GIMI *aGIMIPtr, 
                           const int aInterfaceMinor)
  : CSync(1,1), // Max One Mutex, Max one Condition
    CThread(1), // Max one Thread.
    CMaCI(aGIMIPtr, GIMI_PROTOCOL_MACI_SQL, aInterfaceMinor),
    iSQLDataSequence(0),
    iSQLCommandSequence(0),
    iLastSQLData(),
    iSQLClientCallback(NULL)
{
  dPrint(4,"CSQLClient %p constructed", this);
}
//*****************************************************************************

CSQLClient::~CSQLClient()
{
  DoClose();
  dPrint(4,"CSQLClient %p destructed", this);
}
//*****************************************************************************

MaCI::EMaCIError CSQLClient::DoOpen(void)
{

  EMaCIError result = KMaCIError;
  
  // Checks.
  if(!IsActive()) {

    // Do Subs. using the MaCI provided function.
    result = SubscribeToInterface();

    // If all inits were fine...
    if (result == KMaCIOK) {
      // Start the Thread
      SetActive(true);
      EnableSynchronousMessageReply();
      CThread::RunThread();
      dPrint(4,"CSQLClient::DoOpen() was succesfull.");
    }

  } else {
    dPrint(4,"SQLClient already Active, not Opening again.");
    result = KMaCINotActive;

  }
  
  return result;
}
//*****************************************************************************

MaCI::EMaCIError CSQLClient::DoClose(void)
{
  EMaCIError result = KMaCIError;
  
  if(IsActive()) {
    SetActive(false);

    // Wait for thread to complete.
    CThread::SetRequestTermination();
    /* CThread::CancelThread(); //Removed by script */
    CThread::WaitThread();
    result = UnsubscribeToInterface(TimeoutValue(2000));
  
    if(result == KMaCIOK){
      dPrint(4,"Succesfully closed SQLClient");    
    }else{
      dPrint(4,"Unsubscribing failed!");
    }
    
  } else {
    dPrint(4, "SQLClient not active, so not Closing.");
    result = KMaCINotActive;

  }
  
  return result;
}
//*****************************************************************************

bool CSQLClient::SendQuery(const CSQLQuery &aQuery, unsigned int &aQueryID)
{
  bool result = true;
  CSQLData sqld;
  sqld.CreateInternalBinBag();

  // Get unique MessageID.
  aQueryID = GetUniqueMessageID();

  // Construct Data element with Timestamp, Query and Command.
  result &= sqld.SetTimestamp(Common::TTimestamp());
  result &= sqld.SetCommand(TCommand(KCommandExecuteSQLQuery, aQueryID));
  result &= sqld.SetSQLQueryString(aQuery.GetQueryString());

  // If contruction succeeded, attempt to send message.
  if (result) {
    result = (SendInterfaceMessage(sqld.GetBinBagContainerPtr()->GetBuffer(),
                                   sqld.GetBinBagContainerPtr()->GetBufferSize(),
                                   aQueryID) == KMaCIOK);
  } else {
    dPrint(ODERROR,"Failed to construct SQLData container with given parameters! Nothing sent.");
    
  }

  return result;
}
//*****************************************************************************

bool CSQLClient::GetQueryResult(CSQLResult &aSQLResult,
                                const unsigned int aQueryID,
                                const unsigned int aTimeout_ms)
{
  // Now, get replies for ALL! (In this example, we require ALL or NOTHING)
  CSQLData sqld;
  bool result = false;
  EMaCIError r;
  SMessageSource ms; // Compulsory for call to
                     // Receivesynchronousmessagereply, not used here
                     // though.
  
  // Call the ReceiveMessage wrapper with 2s timeout
  r = ReceiveSynchronousMessageReply(sqld, ms, aQueryID, aTimeout_ms);

  // If result is OK, process the msg.
  if (r == KMaCIOK) {
    // Got message OK, attempt to convert to container.
    result = sqld.GetSQLResult(aSQLResult);
  }
  
  return result;
}
//*****************************************************************************

bool CSQLClient::ExecuteQuery(CSQLResult &aResult,
                              const CSQLQuery &aQuery,
                              const unsigned int aTimeout_ms)
{
  bool result;
  unsigned int queryID;
  const ownTime_ms_t begin = ownTime_get_ms();

  result = SendQuery(aQuery, queryID);
  if (result) {
    ownTime_ms_delta_t tleft = ownTime_get_ms_left(aTimeout_ms, begin);
    if (tleft > 0) {
      result = GetQueryResult(aResult, queryID, tleft);

    } else {
      dPrint(ODWARN,
             "Timeout hit before entering GetQueryResult() - using too low timeout? (Got %u ms)",
             aTimeout_ms);
      result = false;
    }
  }


  return result;
}
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
/**
 * This function is an _EXAMPLE_ of a directly receiving
 * function. When this function model is used, the Client class
 * doesn't have to implement a separate thread. (ProcessMessage and
 * ThreadFunction are not used). However, this means that no special
 * processing can be done by the interface hence this model is only
 * suitable for simple interfaces. This can ofcourse be later changed
 * without changing the public interface, so it's not a
 * architecturally significant decision. Use of this model is also
 * encouraged if possible, as it saves one extra thread thus saving a
 * (minimal) fraction of system resources.
 *
 * As this SQLClient uses the more complex processing model as
 * example, this code block is disabled with precompiler directive,
 * but left here as on fully working example of receiving MaCI
 * dataelements directly from GIMI.
 */
#if 0
bool CSQLClient::GetSQLEvent(CSQLData &aData,
                                 const unsigned int aTimeout_ms);
{
  EMaCIError result;
  gimi::GIMIMessage gmsg;
  
  if (IsActive()) {
    
    // Call the ReceiveMessage wrapper with 2s timeout
    result = ReceiveInterfaceMessage(gmsg, aTimeout_ms);
    
    // If result is OK, process the msg.
    if (result == KMaCIOK) {
      bool r;
      gim::binbag::CBinBag bb;
      CSQLData d;
      
      // Decode BinBag.
      r = bb.Decode(gmsg.getData(), gmsg.getDatalength());
      if (r) {
        // BinBag OK. Decode SQLData.
        r = d.DecodeFrom(&bb);
        if (r && d.GetSQLEvent()) {
          // SQLData ok. Copy to caller.
          aData.Copy(d);
          
        } else {
          result = KMaCIInvalidFormat;
          
        }
        
      } else {
        result = KMaCIInvalidFormat;
        
      }
    }
  } else {
    result = KMaCINotActive;

  }
  
  return (result == KMaCIOK);
}
#endif
//*****************************************************************************
#if 0

bool CSQLClient::GetCommandReply(CSQLData &aData, const int aMessageID, 
                                   const int aTimeout_ms)
{ 
  EMaCIError result;
  SMessageSource ms; // Compulsory for call to
                     // Receivesynchronousmessagereply, not used here
                     // though.

  // Call the ReceiveMessage wrapper with 2s timeout
  result = ReceiveSynchronousMessageReply(aData, ms, aMessageID, aTimeout_ms);
  
  // If result is OK, process the msg.
  if (result == KMaCIOK) {
    // Got message OK.  Basicly we don't need to do anything here, but
    // some interface may want to do some checks: for example, the
    // received message contains some specific element or information
    // before it is accepted.
  }
  
  return (result == KMaCIOK);
}
//*****************************************************************************

bool CSQLClient::SendCommand(const CSQLData &aSQLData, const int aMessageID)
{
  EMaCIError result = KMaCIError;
  
  if (IsActive()) {
    if (aSQLData.GetCommand()) {
      // Send.
      SendInterfaceMessage(aSQLData.GetBinBagContainerPtr()->GetBuffer(),
                           aSQLData.GetBinBagContainerPtr()->GetBufferSize(),
                           aMessageID);
      
      dPrint(10,"SendInterfaceMessage called: %d:%d (%d bytes of payload sent)",
             iInterfaceMajor, iInterfaceMinor, 
             aSQLData.GetBinBagContainerPtr()->GetBufferSize());
      // Result
      result = KMaCIOK;
      
    } else {
      dPrint(2,"No 'TCommand' element in provided CSQLData object. Will not send!");
      result = KMaCIInvalidFormat;

    }
   
  } else {
    dPrint(2,"Unable to send SQLData - Interface is not active! (Open() not called?)");
    result = KMaCINotActive;

  }


  return (result == KMaCIOK);
}
#endif
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************

int CSQLClient::ProcessMessage(const gimi::GIMIMessage &msg)
{
  int result = 0;
  gim::binbag::CBinBag bb;
  CSQLData id;
  bool r;

  r = bb.Decode(msg.getData(), msg.getDatalength());
  if (r) {
    // Succesfully decoded as BinBag.
    r = id.DecodeFrom(&bb);
    if (r) {
      // Succesfully decoded as SQL, now handle contents
      Lock();
      Unlock();
      
      // Call the handler if set.
      if (iSQLClientCallback) {
        dPrint(8,"Got Callback for SQLDataEvent - executing!");
        iSQLClientCallback->OnSQLDataEvent(id,
                                           iSQLDataSequence,
                                           *this);
        dPrint(8,"Callback for SQLDataEvent - execution complete!");
      } 

    } else {
      dPrint(4,"WARNING: Received SQL interface message, but failed to decode as SQLData!");
      
    }
  }
  
  return result;
}

//*****************************************************************************

int CSQLClient::ThreadFunction(const int aThreadNumber)
{
  int result = 0;
  const unsigned int hard_error_count_limit = 10;
  unsigned int hard_error_count = 0;
  EMaCIError e;
  gimi::GIMIMessage gmsg;
  
  assert(aThreadNumber == 0);
  assert(iGIMIPtr != NULL);
  
  dPrint(8, "GIMIMessage handler started");
  
  // Run as long as the thread should be active
  while(IsActive()) {
    // Call the ReceiveMessage wrapper with 1s timeout
    e = ReceiveInterfaceMessage(gmsg, 1000);
    if (e == KMaCIOK) {
      ProcessMessage(gmsg);

      // Reset error counter.
      if (hard_error_count) hard_error_count = 0;

    } else if (e != KMaCITimeout) {
      // Increment hard error count
      ++hard_error_count;
      
      // Check whether the hard error count limit is still under limit. 
      if (hard_error_count < hard_error_count_limit) {
        // Other error, try to recover by sleeping one second.
        dPrint(10,"ProcessMessage returned error %u, trying to recover by sleeping 1000ms (%u attempts left)",
               e, hard_error_count_limit-hard_error_count);
        ownSleep_ms(1000);

      } else {
        dPrint(3,"Error Recovery failed, SQLClient ThreadFunction terminating...");

        // Break the while().
        break;
      }
      
    }
  }
  
  dPrint(8, "GIMIMessage handler stopped");
  SetActive(false);

  return result;
}
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
